package cn.iluwen.airline.Controllers;

import cn.iluwen.airline.Config.CookieUtil;
import cn.iluwen.airline.DTOs.BaseResponse;
import cn.iluwen.airline.DTOs.admin.request.*;
import cn.iluwen.airline.DTOs.admin.response.*;
import cn.iluwen.airline.DTOs.user.response.UserProfileResponse;
import cn.iluwen.airline.DTOs.user.response.OrderResponse;
import cn.iluwen.airline.Entities.Administrator;
import cn.iluwen.airline.Entities.Airport;
import cn.iluwen.airline.Entities.Flight;
import cn.iluwen.airline.Entities.Seat;
import cn.iluwen.airline.Entities.User;
import cn.iluwen.airline.Entities.UserRegistration;
import cn.iluwen.airline.Entities.Order;
import cn.iluwen.airline.Services.AdminService;
import cn.iluwen.airline.Services.AirportService;
import cn.iluwen.airline.Services.FlightService;
import cn.iluwen.airline.Services.SeatService;
import cn.iluwen.airline.Services.UserRegistrationService;
import cn.iluwen.airline.Services.UserService;
import cn.iluwen.airline.Services.OrderService;
import cn.iluwen.airline.utils.PageUtils;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员相关API控制器
 */
@Tag(name = "管理员API", description = "管理员相关的API接口")
@RestController
@RequestMapping("/api/v1/admin")
public class AdminController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRegistrationService userRegistrationService;
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private FlightService flightService;
    
    @Autowired
    private AirportService airportService;
    
    @Autowired
    private SeatService seatService;
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 管理员登录
     */
    @Operation(summary = "管理员登录", description = "管理员登录并获取Cookie认证")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登录成功"),
        @ApiResponse(responseCode = "401", description = "登录失败，用户名或密码错误")
    })
    @PostMapping("/login")
    public ResponseEntity<BaseResponse<AdminLoginResponse>> login(
            @RequestBody AdminLoginRequest request,
            HttpServletResponse response) {
        try {
            // 调用管理员登录服务
            Administrator admin = adminService.login(request.getUsername(), request.getPassword());
            
            // 设置管理员Cookie (使用CookieUtil，只设置一次)
            CookieUtil.setCookie(response, "adminId", admin.getAdminId(), 12 * 60 * 60); // 12小时过期
            
            // 构建登录响应
            AdminLoginResponse loginResponse = new AdminLoginResponse();
            loginResponse.setAdminId(admin.getAdminId());
            loginResponse.setUsername(admin.getUsername());
            loginResponse.setEmail(admin.getEmail());
            
            return ResponseEntity.ok(BaseResponse.success(loginResponse));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 获取用户列表
     */
    @Operation(summary = "获取用户列表", description = "分页获取所有用户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @GetMapping("/users")
    public ResponseEntity<BaseResponse<UserListResponse>> getUserList(
            HttpServletRequest request,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "0") int pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 实现分页查询
            PageInfo<User> pageInfo;
            
            // 根据查询条件选择不同的查询方法
            if (username != null && !username.isEmpty()) {
                pageInfo = userService.getUsersByUsernameLike(username, pageNum, pageSize);
            } else if (email != null && !email.isEmpty()) {
                pageInfo = userService.getUsersByEmailLike(email, pageNum, pageSize);
            } else {
                pageInfo = userService.getUsersWithPaging(pageNum, pageSize);
            }
            
            // 构建响应
            UserListResponse response = new UserListResponse();
            response.setTotal(pageInfo.getTotal());
            response.setPages(pageInfo.getPages());
            response.setPageNum(pageInfo.getPageNum());
            response.setPageSize(pageInfo.getPageSize());
            
            List<UserListResponse.UserItem> items = new ArrayList<>();
            for (User user : pageInfo.getList()) {
                UserListResponse.UserItem item = new UserListResponse.UserItem();
                item.setUserId(user.getUserId());
                item.setUsername(user.getUsername());
                item.setEmail(user.getEmail());
                item.setPhone(user.getPhone());
                item.setRealName(user.getRealName());
                item.setIdCard(user.getIdCard());
                item.setCreatedAt(user.getCreatedAt());
                item.setUpdatedAt(user.getUpdatedAt());
                
                items.add(item);
            }
            response.setList(items);
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 获取注册记录列表
     */
    @Operation(summary = "获取注册记录列表", description = "分页获取所有注册记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @GetMapping("/registrations")
    public ResponseEntity<BaseResponse<RegistrationListResponse>> getRegistrationList(
            HttpServletRequest request,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "0") int pageSize) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 实现分页查询
            PageUtils.startPage(pageNum, pageSize);
            List<UserRegistration> registrationList = userRegistrationService.getAllRegistrations();
            PageInfo<UserRegistration> pageInfo = PageUtils.getPageInfo(registrationList);
            
            // 构建响应
            RegistrationListResponse response = new RegistrationListResponse();
            response.setTotal(pageInfo.getTotal());
            response.setPages(pageInfo.getPages());
            response.setPageNum(pageInfo.getPageNum());
            response.setPageSize(pageInfo.getPageSize());
            
            List<RegistrationListResponse.RegistrationItem> items = new ArrayList<>();
            for (UserRegistration registration : pageInfo.getList()) {
                RegistrationListResponse.RegistrationItem item = new RegistrationListResponse.RegistrationItem();
                item.setRegistrationId(registration.getRegistrationId());
                item.setUserId(registration.getRegistrationId()); // 使用注册ID作为用户ID
                item.setUsername(registration.getUsername()); // 使用用户名
                item.setRegistrationDate(registration.getRegistrationDate());
                item.setRegistrationIp(registration.getRegistrationIp());
                item.setRegistrationSource(registration.getRegistrationSource());                
                items.add(item);
            }
            response.setList(items);
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 删除注册记录
     */
    @Operation(summary = "删除注册记录", description = "删除指定ID的注册记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "注册记录不存在")
    })
    @DeleteMapping("/registrations/{registrationId}")
    public ResponseEntity<BaseResponse<Void>> deleteRegistration(
            HttpServletRequest request,
            @PathVariable String registrationId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 删除注册记录
            boolean success = userRegistrationService.deleteRegistration(registrationId);
            
            if (success) {
                return ResponseEntity.ok(BaseResponse.success());
            } else {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "注册记录不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 管理员登出
     */
    @Operation(summary = "管理员登出", description = "退出登录并清除认证Cookie")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登出成功")
    })
    @PostMapping("/logout")
    public ResponseEntity<BaseResponse<Void>> logout(HttpServletResponse response) {
        // 删除Cookie
        CookieUtil.deleteCookie(response, "adminId");
        return ResponseEntity.ok(BaseResponse.success());
    }
    
    /**
     * 批准用户注册
     */
    @Operation(summary = "批准用户注册", description = "管理员批准或拒绝用户注册申请")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功"),
        @ApiResponse(responseCode = "400", description = "操作失败，请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "注册记录不存在")
    })
    @PostMapping("/approve-user")
    public ResponseEntity<BaseResponse<ApproveUserResponse>> approveUser(
            HttpServletRequest request,
            @RequestBody ApproveUserRequest approveRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 查找注册记录
            UserRegistration registration = userRegistrationService.findById(approveRequest.getRegistrationId());
            if (registration == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "注册记录不存在"));
            }
            
            ApproveUserResponse response = new ApproveUserResponse();
            LocalDateTime now = LocalDateTime.now();
            
            // 判断是否批准
            if (approveRequest.getApproved()) {
                // 批准：创建用户，删除注册记录
                try {
                    // 创建用户
                    User user = userService.createUserFromRegistration(registration);
                    
                    // 删除注册记录
                    userRegistrationService.deleteRegistration(registration.getRegistrationId());
                    
                    // 设置响应
                    response.setUserId(user.getUserId());
                    response.setUsername(user.getUsername());
                    response.setResult("approved");
                    response.setOperationTime(now.format(DateTimeFormatter.ISO_DATE_TIME));
                    
                    return ResponseEntity.ok(BaseResponse.success(response));
                } catch (Exception e) {
                    return ResponseEntity.badRequest()
                            .body(BaseResponse.error(400, "创建用户失败: " + e.getMessage()));
                }
            } else {
                // 拒绝：直接删除注册记录
                userRegistrationService.deleteRegistration(registration.getRegistrationId());
                
                // 设置响应
                response.setUserId(null);
                response.setUsername(registration.getUsername());
                response.setResult("rejected");
                response.setOperationTime(now.format(DateTimeFormatter.ISO_DATE_TIME));
                
                return ResponseEntity.ok(BaseResponse.success(response));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    // =================== 航班管理 ===================
    
    /**
     * 获取航班列表
     */
    @Operation(summary = "获取航班列表", description = "分页获取所有航班")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @GetMapping("/flights")
    public ResponseEntity<BaseResponse<FlightListResponse>> getFlightList(
            HttpServletRequest request,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "0") int pageSize,
            @RequestParam(required = false) String flightNumber,
            @RequestParam(required = false) String departureAirportId,
            @RequestParam(required = false) String arrivalAirportId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 实现分页查询
            PageInfo<Flight> pageInfo;
            
            // 根据查询条件选择不同的查询方法
            if (flightNumber != null && !flightNumber.isEmpty()) {
                pageInfo = flightService.getFlightsByFlightNumberLike(flightNumber, pageNum, pageSize);
            } else if (departureAirportId != null && !departureAirportId.isEmpty() 
                    && arrivalAirportId != null && !arrivalAirportId.isEmpty()) {
                pageInfo = flightService.getFlightsByRoute(departureAirportId, arrivalAirportId, pageNum, pageSize);
            } else {
                pageInfo = flightService.getFlightsWithPaging(pageNum, pageSize);
            }
            
            // 构建响应
            FlightListResponse response = new FlightListResponse();
            response.setTotal(pageInfo.getTotal());
            response.setPages(pageInfo.getPages());
            response.setPageNum(pageInfo.getPageNum());
            response.setPageSize(pageInfo.getPageSize());
            
            List<FlightListResponse.FlightItem> items = new ArrayList<>();
            for (Flight flight : pageInfo.getList()) {
                // 构建FlightItem对象
                FlightListResponse.FlightItem item = new FlightListResponse.FlightItem();
                item.setFlightId(flight.getFlightId());
                item.setFlightNumber(flight.getFlightNumber());
                
                // 获取出发机场信息
                Airport departureAirport = airportService.getAirportById(flight.getDepartureAirportId());
                if (departureAirport != null) {
                    item.setDepartureAirportCode(departureAirport.getAirportCode());
                    item.setDepartureCity(departureAirport.getCity());
                }
                
                // 获取到达机场信息
                Airport arrivalAirport = airportService.getAirportById(flight.getArrivalAirportId());
                if (arrivalAirport != null) {
                    item.setArrivalAirportCode(arrivalAirport.getAirportCode());
                    item.setArrivalCity(arrivalAirport.getCity());
                }
                
                item.setDepartureTime(flight.getDepartureTime());
                item.setArrivalTime(flight.getArrivalTime());
                item.setEconomyPrice(flight.getEconomyPrice());
                item.setBusinessPrice(flight.getBusinessPrice());
                item.setStatus(flight.getStatus());
                
                items.add(item);
            }
            response.setList(items);
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 获取航班详情
     */
    @Operation(summary = "获取航班详情", description = "获取指定ID的航班详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "航班不存在")
    })
    @GetMapping("/flights/{flightId}")
    public ResponseEntity<BaseResponse<FlightResponse>> getFlightDetail(
            HttpServletRequest request,
            @PathVariable String flightId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取航班详情
            Flight flight = flightService.getFlightById(flightId);
            if (flight == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "航班不存在"));
            }
            
            // 构建响应
            FlightResponse response = new FlightResponse();
            response.setFlightId(flight.getFlightId());
            response.setFlightNumber(flight.getFlightNumber());
            response.setDepartureAirportId(flight.getDepartureAirportId());
            response.setArrivalAirportId(flight.getArrivalAirportId());
            
            // 获取出发机场信息
            Airport departureAirport = airportService.getAirportById(flight.getDepartureAirportId());
            if (departureAirport != null) {
                response.setDepartureAirportCode(departureAirport.getAirportCode());
                response.setDepartureAirportName(departureAirport.getAirportName());
                response.setDepartureCity(departureAirport.getCity());
            }
            
            // 获取到达机场信息
            Airport arrivalAirport = airportService.getAirportById(flight.getArrivalAirportId());
            if (arrivalAirport != null) {
                response.setArrivalAirportCode(arrivalAirport.getAirportCode());
                response.setArrivalAirportName(arrivalAirport.getAirportName());
                response.setArrivalCity(arrivalAirport.getCity());
            }
            
            response.setDepartureTime(flight.getDepartureTime());
            response.setArrivalTime(flight.getArrivalTime());
            response.setEconomyPrice(flight.getEconomyPrice());
            response.setBusinessPrice(flight.getBusinessPrice());
            response.setTotalEconomySeats(flight.getTotalEconomySeats());
            response.setTotalBusinessSeats(flight.getTotalBusinessSeats());
            response.setStatus(flight.getStatus());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 添加航班
     */
    @Operation(summary = "添加航班", description = "添加新航班")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "添加成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @PostMapping("/flights")
    public ResponseEntity<BaseResponse<FlightResponse>> addFlight(
            HttpServletRequest request,
            @RequestBody AddFlightRequest flightRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 检查必要参数
            if (flightRequest.getFlightNumber() == null || flightRequest.getFlightNumber().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "航班号不能为空"));
            }
            if (flightRequest.getDepartureAirportId() == null || flightRequest.getDepartureAirportId().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "出发机场ID不能为空"));
            }
            if (flightRequest.getArrivalAirportId() == null || flightRequest.getArrivalAirportId().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "到达机场ID不能为空"));
            }
            if (flightRequest.getDepartureTime() == null) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "起飞时间不能为空"));
            }
            if (flightRequest.getArrivalTime() == null) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "到达时间不能为空"));
            }
            
            // 检查机场是否存在
            Airport departureAirport = airportService.getAirportById(flightRequest.getDepartureAirportId());
            if (departureAirport == null) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "出发机场不存在"));
            }
            
            Airport arrivalAirport = airportService.getAirportById(flightRequest.getArrivalAirportId());
            if (arrivalAirport == null) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "到达机场不存在"));
            }
            
            // 检查起飞时间是否晚于到达时间
            if (flightRequest.getDepartureTime().isAfter(flightRequest.getArrivalTime())) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "起飞时间不能晚于到达时间"));
            }
            
            // 创建航班对象
            Flight flight = new Flight();
            flight.setFlightNumber(flightRequest.getFlightNumber());
            flight.setDepartureAirportId(flightRequest.getDepartureAirportId());
            flight.setArrivalAirportId(flightRequest.getArrivalAirportId());
            flight.setDepartureTime(flightRequest.getDepartureTime());
            flight.setArrivalTime(flightRequest.getArrivalTime());
            flight.setEconomyPrice(flightRequest.getEconomyPrice());
            flight.setBusinessPrice(flightRequest.getBusinessPrice());
            flight.setTotalEconomySeats(flightRequest.getTotalEconomySeats());
            flight.setTotalBusinessSeats(flightRequest.getTotalBusinessSeats());
            flight.setStatus(flightRequest.getStatus());
            
            // 添加航班
            flight = flightService.addFlight(flight);
            
            // 构建响应
            FlightResponse response = new FlightResponse();
            response.setFlightId(flight.getFlightId());
            response.setFlightNumber(flight.getFlightNumber());
            response.setDepartureAirportId(flight.getDepartureAirportId());
            response.setArrivalAirportId(flight.getArrivalAirportId());
            response.setDepartureAirportCode(departureAirport.getAirportCode());
            response.setDepartureAirportName(departureAirport.getAirportName());
            response.setDepartureCity(departureAirport.getCity());
            response.setArrivalAirportCode(arrivalAirport.getAirportCode());
            response.setArrivalAirportName(arrivalAirport.getAirportName());
            response.setArrivalCity(arrivalAirport.getCity());
            response.setDepartureTime(flight.getDepartureTime());
            response.setArrivalTime(flight.getArrivalTime());
            response.setEconomyPrice(flight.getEconomyPrice());
            response.setBusinessPrice(flight.getBusinessPrice());
            response.setTotalEconomySeats(flight.getTotalEconomySeats());
            response.setTotalBusinessSeats(flight.getTotalBusinessSeats());
            response.setStatus(flight.getStatus());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 更新航班信息
     */
    @Operation(summary = "更新航班信息", description = "更新指定ID的航班信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "航班不存在")
    })
    @PutMapping("/flights/{flightId}")
    public ResponseEntity<BaseResponse<FlightResponse>> updateFlight(
            HttpServletRequest request,
            @PathVariable String flightId,
            @RequestBody AddFlightRequest flightRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取航班信息
            Flight flight = flightService.getFlightById(flightId);
            if (flight == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "航班不存在"));
            }
            
            // 更新航班信息
            flight.setFlightNumber(flightRequest.getFlightNumber());
            flight.setDepartureAirportId(flightRequest.getDepartureAirportId());
            flight.setArrivalAirportId(flightRequest.getArrivalAirportId());
            flight.setDepartureTime(flightRequest.getDepartureTime());
            flight.setArrivalTime(flightRequest.getArrivalTime());
            flight.setEconomyPrice(flightRequest.getEconomyPrice());
            flight.setBusinessPrice(flightRequest.getBusinessPrice());
            flight.setTotalEconomySeats(flightRequest.getTotalEconomySeats());
            flight.setTotalBusinessSeats(flightRequest.getTotalBusinessSeats());
            flight.setStatus(flightRequest.getStatus());
            
            // 更新航班
            flight = flightService.updateFlight(flight);
            
            // 获取相关机场信息
            Airport departureAirport = airportService.getAirportById(flight.getDepartureAirportId());
            Airport arrivalAirport = airportService.getAirportById(flight.getArrivalAirportId());
            
            // 构建响应
            FlightResponse response = new FlightResponse();
            response.setFlightId(flight.getFlightId());
            response.setFlightNumber(flight.getFlightNumber());
            response.setDepartureAirportId(flight.getDepartureAirportId());
            response.setArrivalAirportId(flight.getArrivalAirportId());
            
            if (departureAirport != null) {
                response.setDepartureAirportCode(departureAirport.getAirportCode());
                response.setDepartureAirportName(departureAirport.getAirportName());
                response.setDepartureCity(departureAirport.getCity());
            }
            
            response.setArrivalAirportCode(arrivalAirport.getAirportCode());
            
            if (arrivalAirport != null) {
                response.setArrivalAirportName(arrivalAirport.getAirportName());
                response.setArrivalCity(arrivalAirport.getCity());
            }
            
            response.setDepartureTime(flight.getDepartureTime());
            response.setArrivalTime(flight.getArrivalTime());
            response.setEconomyPrice(flight.getEconomyPrice());
            response.setBusinessPrice(flight.getBusinessPrice());
            response.setTotalEconomySeats(flight.getTotalEconomySeats());
            response.setTotalBusinessSeats(flight.getTotalBusinessSeats());
            response.setStatus(flight.getStatus());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 更新航班状态
     */
    @Operation(summary = "更新航班状态", description = "更新指定ID的航班状态")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "航班不存在")
    })
    @PutMapping("/flights/{flightId}/status")
    public ResponseEntity<BaseResponse<Void>> updateFlightStatus(
            HttpServletRequest request,
            @PathVariable String flightId,
            @RequestParam String status) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取航班信息
            Flight flight = flightService.getFlightById(flightId);
            if (flight == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "航班不存在"));
            }
            
            // 检查状态值是否合法
            if (!status.equals("scheduled") && !status.equals("delayed") && 
                !status.equals("cancelled") && !status.equals("completed")) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "无效的航班状态值"));
            }
            
            // 更新航班状态
            flightService.updateFlightStatus(flightId, status);
            
            return ResponseEntity.ok(BaseResponse.success());
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 删除航班
     */
    @Operation(summary = "删除航班", description = "删除指定ID的航班")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "航班不存在")
    })
    @DeleteMapping("/flights/{flightId}")
    public ResponseEntity<BaseResponse<Void>> deleteFlight(
            HttpServletRequest request,
            @PathVariable String flightId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取航班信息
            Flight flight = flightService.getFlightById(flightId);
            if (flight == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "航班不存在"));
            }
            
            // 删除航班
            boolean success = flightService.deleteFlight(flightId);
            if (!success) {
                return ResponseEntity.status(500)
                        .body(BaseResponse.error(500, "删除航班失败"));
            }
            
            return ResponseEntity.ok(BaseResponse.success());
        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(BaseResponse.error(500, e.getMessage()));
        }
    }
    
    // =================== 机场管理 ===================
    
    /**
     * 获取机场列表
     */
    @Operation(summary = "获取机场列表", description = "分页获取所有机场")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @GetMapping("/airports")
    public ResponseEntity<BaseResponse<AirportListResponse>> getAirportList(
            HttpServletRequest request,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "0") int pageSize,
            @RequestParam(required = false) String airportName,
            @RequestParam(required = false) String city) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 实现分页查询
            PageInfo<Airport> pageInfo;
            
            // 根据查询条件选择不同的查询方法
            if (airportName != null && !airportName.isEmpty()) {
                pageInfo = airportService.getAirportsByNameLike(airportName, pageNum, pageSize);
            } else if (city != null && !city.isEmpty()) {
                pageInfo = airportService.getAirportsByCityLike(city, pageNum, pageSize);
            } else {
                pageInfo = airportService.getAirportsWithPaging(pageNum, pageSize);
            }
            
            // 构建响应
            AirportListResponse response = new AirportListResponse();
            response.setTotal(pageInfo.getTotal());
            response.setPages(pageInfo.getPages());
            response.setPageNum(pageInfo.getPageNum());
            response.setPageSize(pageInfo.getPageSize());
            
            List<AirportListResponse.AirportItem> items = new ArrayList<>();
            for (Airport airport : pageInfo.getList()) {
                AirportListResponse.AirportItem item = new AirportListResponse.AirportItem();
                item.setAirportId(airport.getAirportId());
                item.setAirportCode(airport.getAirportCode());
                item.setAirportName(airport.getAirportName());
                item.setCity(airport.getCity());
                
                items.add(item);
            }
            response.setList(items);
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 获取机场详情
     */
    @Operation(summary = "获取机场详情", description = "获取指定ID的机场详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "机场不存在")
    })
    @GetMapping("/airports/{airportId}")
    public ResponseEntity<BaseResponse<AirportResponse>> getAirportDetail(
            HttpServletRequest request,
            @PathVariable String airportId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取机场详情
            Airport airport = airportService.getAirportById(airportId);
            if (airport == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "机场不存在"));
            }
            
            // 构建响应
            AirportResponse response = new AirportResponse();
            response.setAirportId(airport.getAirportId());
            response.setAirportCode(airport.getAirportCode());
            response.setAirportName(airport.getAirportName());
            response.setCity(airport.getCity());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 添加机场
     */
    @Operation(summary = "添加机场", description = "添加新机场")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "添加成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @PostMapping("/airports")
    public ResponseEntity<BaseResponse<AirportResponse>> addAirport(
            HttpServletRequest request,
            @RequestBody AddAirportRequest airportRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 检查必要参数
            if (airportRequest.getAirportCode() == null || airportRequest.getAirportCode().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "机场三字码不能为空"));
            }
            if (airportRequest.getAirportName() == null || airportRequest.getAirportName().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "机场名称不能为空"));
            }
            if (airportRequest.getCity() == null || airportRequest.getCity().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "城市不能为空"));
            }
            
            // 检查机场三字码是否已存在
            Airport existingAirport = airportService.getAirportByCode(airportRequest.getAirportCode());
            if (existingAirport != null) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "机场三字码已存在: " + airportRequest.getAirportCode()));
            }
            
            // 创建机场对象
            Airport airport = new Airport();
            airport.setAirportCode(airportRequest.getAirportCode());
            airport.setAirportName(airportRequest.getAirportName());
            airport.setCity(airportRequest.getCity());
            
            // 添加机场
            airport = airportService.addAirport(airport);
            
            // 构建响应
            AirportResponse response = new AirportResponse();
            response.setAirportId(airport.getAirportId());
            response.setAirportCode(airport.getAirportCode());
            response.setAirportName(airport.getAirportName());
            response.setCity(airport.getCity());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 更新机场信息
     */
    @Operation(summary = "更新机场信息", description = "更新指定ID的机场信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "机场不存在")
    })
    @PutMapping("/airports/{airportId}")
    public ResponseEntity<BaseResponse<AirportResponse>> updateAirport(
            HttpServletRequest request,
            @PathVariable String airportId,
            @RequestBody AddAirportRequest airportRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取机场信息
            Airport airport = airportService.getAirportById(airportId);
            if (airport == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "机场不存在"));
            }
            
            // 检查机场三字码是否已被其他机场使用
            if (!airport.getAirportCode().equals(airportRequest.getAirportCode())) {
                Airport existingAirport = airportService.getAirportByCode(airportRequest.getAirportCode());
                if (existingAirport != null) {
                    return ResponseEntity.badRequest()
                            .body(BaseResponse.error(400, "机场三字码已存在: " + airportRequest.getAirportCode()));
                }
            }
            
            // 更新机场信息
            airport.setAirportCode(airportRequest.getAirportCode());
            airport.setAirportName(airportRequest.getAirportName());
            airport.setCity(airportRequest.getCity());
            
            // 更新机场
            airport = airportService.updateAirport(airport);
            
            // 构建响应
            AirportResponse response = new AirportResponse();
            response.setAirportId(airport.getAirportId());
            response.setAirportCode(airport.getAirportCode());
            response.setAirportName(airport.getAirportName());
            response.setCity(airport.getCity());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 删除机场
     */
    @Operation(summary = "删除机场", description = "删除指定ID的机场")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "机场不存在")
    })
    @DeleteMapping("/airports/{airportId}")
    public ResponseEntity<BaseResponse<Void>> deleteAirport(
            HttpServletRequest request,
            @PathVariable String airportId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取机场信息
            Airport airport = airportService.getAirportById(airportId);
            if (airport == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "机场不存在"));
            }
            
            // 删除机场
            boolean success = airportService.deleteAirport(airportId);
            if (!success) {
                return ResponseEntity.status(500)
                        .body(BaseResponse.error(500, "删除机场失败"));
            }
            
            return ResponseEntity.ok(BaseResponse.success());
        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(BaseResponse.error(500, e.getMessage()));
        }
    }
    
    // =================== 座位管理 ===================
    
    /**
     * 获取座位列表
     */
    @Operation(summary = "获取座位列表", description = "分页获取所有座位")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @GetMapping("/seats")
    public ResponseEntity<BaseResponse<SeatListResponse>> getSeatList(
            HttpServletRequest request,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "0") int pageSize,
            @RequestParam(required = false) String flightId,
            @RequestParam(required = false) String seatClass) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 实现分页查询
            PageInfo<Seat> pageInfo;
            
            // 根据查询条件选择不同的查询方法
            if (flightId != null && !flightId.isEmpty() && seatClass != null && !seatClass.isEmpty()) {
                pageInfo = seatService.getSeatsByFlightIdAndClass(flightId, seatClass, pageNum, pageSize);
            } else if (flightId != null && !flightId.isEmpty()) {
                pageInfo = seatService.getSeatsByFlightId(flightId, pageNum, pageSize);
            } else {
                pageInfo = seatService.getSeatsWithPaging(pageNum, pageSize);
            }
            
            // 构建响应
            SeatListResponse response = new SeatListResponse();
            response.setTotal(pageInfo.getTotal());
            response.setPages(pageInfo.getPages());
            response.setPageNum(pageInfo.getPageNum());
            response.setPageSize(pageInfo.getPageSize());
            
            // 优化：收集所有需要的flightId
            List<Seat> seatList = pageInfo.getList();
            List<String> flightIds = seatList.stream()
                .map(Seat::getFlightId)
                .distinct()
                .collect(java.util.stream.Collectors.toList());
            
            // 优化：一次性查询所有相关的航班
            Map<String, Flight> flightMap = new HashMap<>();
            if (!flightIds.isEmpty()) {
                List<Flight> flights = flightService.getFlightsByIds(flightIds);
                for (Flight flight : flights) {
                    flightMap.put(flight.getFlightId(), flight);
                }
            }
            
            // 构建座位列表
            List<SeatListResponse.SeatItem> items = new ArrayList<>();
            for (Seat seat : seatList) {
                SeatListResponse.SeatItem item = new SeatListResponse.SeatItem();
                item.setSeatId(seat.getSeatId());
                item.setFlightId(seat.getFlightId());
                
                // 从Map中获取航班信息，避免重复查询
                Flight flight = flightMap.get(seat.getFlightId());
                if (flight != null) {
                    item.setFlightNumber(flight.getFlightNumber());
                }
                
                item.setSeatNumber(seat.getSeatNumber());
                item.setSeatClass(seat.getSeatClass());
                item.setIsOccupied(seat.getIsOccupied());
                
                items.add(item);
            }
            response.setList(items);
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 获取座位详情
     */
    @Operation(summary = "获取座位详情", description = "获取指定ID的座位详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "座位不存在")
    })
    @GetMapping("/seats/{seatId}")
    public ResponseEntity<BaseResponse<SeatResponse>> getSeatDetail(
            HttpServletRequest request,
            @PathVariable String seatId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取座位详情
            Seat seat = seatService.getSeatById(seatId);
            if (seat == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "座位不存在"));
            }
            
            // 构建响应
            SeatResponse response = new SeatResponse();
            response.setSeatId(seat.getSeatId());
            response.setFlightId(seat.getFlightId());
            
            // 获取航班信息 - 优化：只在需要时查询一次
            String flightId = seat.getFlightId();
            if (flightId != null && !flightId.isEmpty()) {
                Flight flight = flightService.getFlightById(flightId);
                if (flight != null) {
                    response.setFlightNumber(flight.getFlightNumber());
                }
            }
            
            response.setSeatNumber(seat.getSeatNumber());
            response.setSeatClass(seat.getSeatClass());
            response.setIsOccupied(seat.getIsOccupied());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 添加座位
     */
    @Operation(summary = "添加座位", description = "添加新座位")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "添加成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @PostMapping("/seats")
    public ResponseEntity<BaseResponse<SeatResponse>> addSeat(
            HttpServletRequest request,
            @RequestBody AddSeatRequest seatRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 检查必要参数
            if (seatRequest.getFlightId() == null || seatRequest.getFlightId().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "航班ID不能为空"));
            }
            if (seatRequest.getSeatNumber() == null || seatRequest.getSeatNumber().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "座位号不能为空"));
            }
            if (seatRequest.getSeatClass() == null || seatRequest.getSeatClass().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "座位舱位不能为空"));
            }
            
            // 检查航班是否存在
            Flight flight = flightService.getFlightById(seatRequest.getFlightId());
            if (flight == null) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "航班不存在"));
            }
            
            // 创建座位对象
            Seat seat = new Seat();
            seat.setFlightId(seatRequest.getFlightId());
            seat.setSeatNumber(seatRequest.getSeatNumber());
            seat.setSeatClass(seatRequest.getSeatClass());
            seat.setIsOccupied(seatRequest.getIsOccupied() != null ? seatRequest.getIsOccupied() : false);
            
            // 添加座位
            seat = seatService.addSeat(seat);
            
            // 构建响应
            SeatResponse response = new SeatResponse();
            response.setSeatId(seat.getSeatId());
            response.setFlightId(seat.getFlightId());
            response.setFlightNumber(flight.getFlightNumber());
            response.setSeatNumber(seat.getSeatNumber());
            response.setSeatClass(seat.getSeatClass());
            response.setIsOccupied(seat.getIsOccupied());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 更新座位信息
     */
    @Operation(summary = "更新座位信息", description = "更新指定ID的座位信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "座位不存在")
    })
    @PutMapping("/seats/{seatId}")
    public ResponseEntity<BaseResponse<SeatResponse>> updateSeat(
            HttpServletRequest request,
            @PathVariable String seatId,
            @RequestBody AddSeatRequest seatRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取座位信息
            Seat seat = seatService.getSeatById(seatId);
            if (seat == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "座位不存在"));
            }
            
            // 更新座位信息
            seat.setFlightId(seatRequest.getFlightId());
            seat.setSeatNumber(seatRequest.getSeatNumber());
            seat.setSeatClass(seatRequest.getSeatClass());
            seat.setIsOccupied(seatRequest.getIsOccupied());
            
            // 更新座位
            seat = seatService.updateSeat(seat);
            
            // 获取航班信息
            Flight flight = flightService.getFlightById(seat.getFlightId());
            
            // 构建响应
            SeatResponse response = new SeatResponse();
            response.setSeatId(seat.getSeatId());
            response.setFlightId(seat.getFlightId());
            if (flight != null) {
                response.setFlightNumber(flight.getFlightNumber());
            }
            response.setSeatNumber(seat.getSeatNumber());
            response.setSeatClass(seat.getSeatClass());
            response.setIsOccupied(seat.getIsOccupied());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 更新座位占用状态
     */
    @Operation(summary = "更新座位占用状态", description = "更新指定ID的座位占用状态")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "座位不存在")
    })
    @PutMapping("/seats/{seatId}/occupied")
    public ResponseEntity<BaseResponse<Void>> updateSeatOccupiedStatus(
            HttpServletRequest request,
            @PathVariable String seatId,
            @RequestParam boolean isOccupied) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取座位信息
            Seat seat = seatService.getSeatById(seatId);
            if (seat == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "座位不存在"));
            }
            
            // 更新座位占用状态
            boolean success = seatService.updateSeatOccupiedStatus(seatId, isOccupied);
            if (!success) {
                return ResponseEntity.status(500)
                        .body(BaseResponse.error(500, "更新座位占用状态失败"));
            }
            
            return ResponseEntity.ok(BaseResponse.success());
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 删除座位
     */
    @Operation(summary = "删除座位", description = "删除指定ID的座位")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "座位不存在")
    })
    @DeleteMapping("/seats/{seatId}")
    public ResponseEntity<BaseResponse<Void>> deleteSeat(
            HttpServletRequest request,
            @PathVariable String seatId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取座位信息
            Seat seat = seatService.getSeatById(seatId);
            if (seat == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "座位不存在"));
            }
            
            // 删除座位
            boolean success = seatService.deleteSeat(seatId);
            if (!success) {
                return ResponseEntity.status(500)
                        .body(BaseResponse.error(500, "删除座位失败"));
            }
            
            return ResponseEntity.ok(BaseResponse.success());
        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(BaseResponse.error(500, e.getMessage()));
        }
    }
    
    /**
     * 获取用户详情
     */
    @Operation(summary = "获取用户详情", description = "获取指定ID的用户详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/users/{userId}")
    public ResponseEntity<BaseResponse<UserProfileResponse>> getUserDetail(
            HttpServletRequest request,
            @PathVariable String userId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取用户详情
            User user = userService.getUserById(userId);
            if (user == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "用户不存在"));
            }
            
            // 构建响应
            UserProfileResponse response = new UserProfileResponse();
            response.setUserId(user.getUserId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            response.setPhone(user.getPhone());
            response.setRealName(user.getRealName());
            response.setIdCard(user.getIdCard());
            response.setCreatedAt(user.getCreatedAt());
            response.setUpdatedAt(user.getUpdatedAt());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 更新用户信息
     */
    @Operation(summary = "更新用户信息", description = "管理员更新指定用户的信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @PutMapping("/users/{userId}")
    public ResponseEntity<BaseResponse<UserProfileResponse>> updateUser(
            HttpServletRequest request,
            @PathVariable String userId,
            @RequestBody UpdateUserRequest updateRequest) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 获取原用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "用户不存在"));
            }
            
            // 更新用户信息
            if (updateRequest.getUsername() != null && !updateRequest.getUsername().isEmpty()) {
                user.setUsername(updateRequest.getUsername());
            }
            if (updateRequest.getEmail() != null && !updateRequest.getEmail().isEmpty()) {
                user.setEmail(updateRequest.getEmail());
            }
            if (updateRequest.getPhone() != null) {
                user.setPhone(updateRequest.getPhone());
            }
            if (updateRequest.getRealName() != null) {
                user.setRealName(updateRequest.getRealName());
            }
            if (updateRequest.getIdCard() != null) {
                user.setIdCard(updateRequest.getIdCard());
            }
            if (updateRequest.getPassword() != null && !updateRequest.getPassword().isEmpty()) {
                user.setPassword(updateRequest.getPassword()); // 密码会在Service层加密
            }
            
            // 保存更新
            user = userService.updateUser(user);
            
            // 构建响应
            UserProfileResponse response = new UserProfileResponse();
            response.setUserId(user.getUserId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            response.setPhone(user.getPhone());
            response.setRealName(user.getRealName());
            response.setIdCard(user.getIdCard());
            response.setCreatedAt(user.getCreatedAt());
            response.setUpdatedAt(user.getUpdatedAt());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 删除用户
     */
    @Operation(summary = "删除用户", description = "管理员删除指定用户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<BaseResponse<Void>> deleteUser(
            HttpServletRequest request,
            @PathVariable String userId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 删除用户
            boolean success = userService.deleteUser(userId);
            
            if (success) {
                return ResponseEntity.ok(BaseResponse.success());
            } else {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "用户不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 获取航班所有座位
     */
    @Operation(summary = "获取航班所有座位", description = "一次性获取指定航班的所有座位和航班信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "航班不存在")
    })
    @GetMapping("/flights/{flightId}/seats")
    public ResponseEntity<BaseResponse<Map<String, Object>>> getFlightSeats(
            HttpServletRequest request,
            @PathVariable String flightId) {
        try {
            // 从请求属性中获取adminId（在拦截器中设置）
            String adminId = (String) request.getAttribute("adminId");
            
            // 检查adminId有效性
            Administrator admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "管理员不存在或未授权"));
            }
            
            // 批量获取航班座位和航班信息
            Map<String, Object> result = seatService.getBatchSeatsByFlightId(flightId);
            
            return ResponseEntity.ok(BaseResponse.success(result));
        } catch (Exception e) {
            if (e.getMessage().contains("航班不存在")) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, e.getMessage()));
            }
            return ResponseEntity.status(500)
                    .body(BaseResponse.error(500, e.getMessage()));
        }
    }

    /// ============ 管理员订单管理 ============

    /**
     * 管理员分页查询所有订单
     */
    @Operation(summary = "查询所有订单", description = "管理员分页查询所有订单，可按状态和关键词筛选")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权")
    })
    @GetMapping("/flights/orders")
    public ResponseEntity<BaseResponse<PageInfo<OrderResponse>>> getAllOrders(
            HttpServletRequest request,
            @RequestParam(defaultValue = "0") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, "管理员未登录"));
        }
        PageInfo<OrderResponse> orders = orderService.getAllOrders(pageNum, pageSize, status, keyword);
        return ResponseEntity.ok(BaseResponse.success(orders));
    }

    /**
     * 管理员获取订单详情
     */
    @Operation(summary = "获取订单详情", description = "管理员获取指定订单的详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "订单不存在")
    })
    @GetMapping("/flights/orders/{orderId}")
    public ResponseEntity<BaseResponse<OrderResponse>> getOrderDetailByAdmin(
            HttpServletRequest request,
            @PathVariable String orderId) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            OrderResponse order = orderService.getOrderDetailByAdmin(orderId);
            if (order == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "订单不存在"));
            }
            return ResponseEntity.ok(BaseResponse.success(order));
        } catch (Exception e) {
            return ResponseEntity.status(404)
                    .body(BaseResponse.error(404, e.getMessage()));
        }
    }

    /**
     * 管理员删除订单
     */
    @Operation(summary = "删除订单", description = "管理员删除指定订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "订单不存在")
    })
    @DeleteMapping("/flights/orders/{orderId}")
    public ResponseEntity<BaseResponse<Void>> deleteOrderByAdmin(
            HttpServletRequest request,
            @PathVariable String orderId) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            boolean success = orderService.deleteOrderByAdmin(orderId);
            if (success) {
                return ResponseEntity.ok(BaseResponse.success());
            } else {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "订单不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(400)
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 管理员修改订单状态
     */
    @Operation(summary = "修改订单状态", description = "管理员修改订单状态")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "订单不存在")
    })
    @PutMapping("/flights/orders/{orderId}/status")
    public ResponseEntity<BaseResponse<Void>> updateOrderStatusByAdmin(
            HttpServletRequest request,
            @PathVariable String orderId,
            @RequestParam String status) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            boolean success = orderService.updateOrderStatusByAdmin(orderId, status);
            if (success) {
            return ResponseEntity.ok(BaseResponse.success());
            } else {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "订单不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(400)
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 管理员取消订单
     */
    @Operation(summary = "取消订单", description = "管理员取消订单（释放座位）")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "订单不存在")
    })
    @PostMapping("/flights/orders/{orderId}/cancel")
    public ResponseEntity<BaseResponse<Void>> cancelOrderByAdmin(
            HttpServletRequest request,
            @PathVariable String orderId) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            boolean success = orderService.cancelOrderByAdmin(orderId);
            if (success) {
            return ResponseEntity.ok(BaseResponse.success());
            } else {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "订单不存在或已取消"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(400)
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }

    // ============ 管理员改签审核 ============

    /**
     * 查询所有待审核改签订单
     */
    @Operation(summary = "查询所有待审核改签订单", description = "管理员分页查询所有待审核改签订单")
    @GetMapping("/flights/orders/reschedule-pending")
    public ResponseEntity<BaseResponse<List<Order>>> getReschedulePendingOrders(HttpServletRequest request) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            adminId = CookieUtil.getCookieValue(request, "adminId");
        }
        if (adminId == null) {
            return ResponseEntity.status(401).body(BaseResponse.error(401, "管理员未登录"));
        }
        List<Order> orders = orderService.getReschedulePendingOrders();
        return ResponseEntity.ok(BaseResponse.success(orders));
    }

    /**
     * 管理员同意改签
     */
    @Operation(summary = "管理员同意改签", description = "管理员审核同意用户改签")
    @PostMapping("/flights/orders/{orderId}/reschedule/approve")
    public ResponseEntity<BaseResponse<String>> approveReschedule(@PathVariable String orderId, HttpServletRequest request) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            adminId = CookieUtil.getCookieValue(request, "adminId");
        }
        if (adminId == null) {
            return ResponseEntity.status(401).body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            orderService.adminApproveReschedule(orderId);
            return ResponseEntity.ok(BaseResponse.success("改签已同意"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 管理员拒绝改签
     */
    @Operation(summary = "管理员拒绝改签", description = "管理员审核拒绝用户改签")
    @PostMapping("/flights/orders/{orderId}/reschedule/reject")
    public ResponseEntity<BaseResponse<String>> rejectReschedule(@PathVariable String orderId, HttpServletRequest request) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            adminId = CookieUtil.getCookieValue(request, "adminId");
        }
        if (adminId == null) {
            return ResponseEntity.status(401).body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            orderService.adminRejectReschedule(orderId);
            return ResponseEntity.ok(BaseResponse.success("改签已拒绝"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(BaseResponse.error(400, e.getMessage()));
        }
    }

    // ============ 管理员退票审核 ============

    /**
     * 查询所有待审核退票订单
     */
    @Operation(summary = "查询所有待审核退票订单", description = "管理员查询所有待审核退票订单")
    @GetMapping("/flights/orders/refund-pending")
    public ResponseEntity<BaseResponse<List<Order>>> getRefundPendingOrders(HttpServletRequest request) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            adminId = CookieUtil.getCookieValue(request, "adminId");
        }
        if (adminId == null) {
            return ResponseEntity.status(401).body(BaseResponse.error(401, "管理员未登录"));
        }
        List<Order> orders = orderService.getRefundPendingOrders();
        return ResponseEntity.ok(BaseResponse.success(orders));
    }

    /**
     * 管理员同意退票
     */
    @Operation(summary = "管理员同意退票", description = "管理员审核同意用户退票申请")
    @PostMapping("/flights/orders/{orderId}/refund/approve")
    public ResponseEntity<BaseResponse<String>> approveRefund(@PathVariable String orderId, HttpServletRequest request) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            adminId = CookieUtil.getCookieValue(request, "adminId");
        }
        if (adminId == null) {
            return ResponseEntity.status(401).body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            orderService.adminApproveRefund(orderId);
            return ResponseEntity.ok(BaseResponse.success("退票已同意"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 管理员拒绝退票
     */
    @Operation(summary = "管理员拒绝退票", description = "管理员审核拒绝用户退票申请")
    @PostMapping("/flights/orders/{orderId}/refund/reject")
    public ResponseEntity<BaseResponse<String>> rejectRefund(@PathVariable String orderId, HttpServletRequest request) {
        String adminId = (String) request.getAttribute("adminId");
        if (adminId == null) {
            adminId = CookieUtil.getCookieValue(request, "adminId");
        }
        if (adminId == null) {
            return ResponseEntity.status(401).body(BaseResponse.error(401, "管理员未登录"));
        }
        try {
            orderService.adminRejectRefund(orderId);
            return ResponseEntity.ok(BaseResponse.success("退票已拒绝"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(BaseResponse.error(400, e.getMessage()));
        }
    }
}
